package main

import (
	"fmt"
	"gitee.com/ling1314/origin-utility/app"
	"github.com/kardianos/service"
	log "github.com/sirupsen/logrus"
	"github.com/urfave/cli/v2"
	"os"
)

const (
	serviceName = "veapp-main-service"
)

func main() {
	fmt.Printf("11")
	cliSrv := cli.NewApp()
	cliSrv.Name = serviceName
	cliSrv.Usage = "veapp-main-service usage"
	cliSrv.Commands = []*cli.Command{
		{
			Name:   "install",
			Action: cliAction,
		},
		{
			Name:   "uninstall",
			Action: cliAction,
		},
		{
			Name:   "start",
			Action: cliAction,
		},
		{
			Name:   "restart",
			Action: cliAction,
		},
		{
			Name:   "stop",
			Action: cliAction,
		},
	}
	cliSrv.Flags = []cli.Flag{
		&cli.StringFlag{
			Name:  "install",
			Value: "install",
			Usage: "Write the files required for startup",
		},
		&cli.StringFlag{
			Name:  "uninstall",
			Value: "uninstall",
			Usage: "Delete startup files",
		},
		&cli.StringFlag{
			Name:  "start",
			Value: "start",
			Usage: "start the service",
		},
		&cli.StringFlag{
			Name:  "stop",
			Value: "stop",
			Usage: "stop the service",
		},
		&cli.StringFlag{
			Name:  "restart",
			Value: "restart",
			Usage: "restart the service",
		},
	}

	cliSrv.Action = startAction

	if err := cliSrv.Run(os.Args); err != nil {
		log.Error(err)
		return
	}
}

type SystemService struct{}

func (p *SystemService) Start(service.Service) error {
	log.Debug("veapp service start")
	go func() {
		err := app.Run()
		if err != nil {
			log.Error(err)
		}
	}()
	return nil
}

func (p *SystemService) Stop(s service.Service) error {
	log.Debug("veapp service stop")
	return nil
}

func createSystemService() (service.Service, error) {
	svcConfig := &service.Config{
		Name:        serviceName,
		DisplayName: "veapp main service DisplayName",
		Description: "veapp main service Description",
	}
	ss := &SystemService{}
	s, err := service.New(ss, svcConfig)
	if err != nil {
		return nil, fmt.Errorf("service New failed, err: %v\n", err)
	}
	return s, nil
}
func cliAction(c *cli.Context) error {
	s, err := createSystemService()
	if err != nil {
		return err
	}
	err = service.Control(s, c.Command.Name)
	if err != nil {
		return err
	}
	return nil
}

func startAction(c *cli.Context) error {
	s, err := createSystemService()
	if err != nil {
		return err
	}
	// 默认 运行 Run
	err = s.Run()
	if err != nil {
		return err
	}
	return nil
}
